#!/bin/bash

# ****************************************************
# validate_mac ()
# Usage:
# if ( validate_mac "$NEW_MAC" )
# then
# 	echo valid
# else
# 	echo invalid
# fi
# ****************************************************
validate_mac ()
{
MAC_TEST=`echo "$1" | sed -n "/^\([0-9A-Fa-f][0-9A-Fa-f]*:\)\{5\}[0-9A-Fa-f][0-9A-Fa-f]*$/p"`
if [ ! "$MAC_TEST" = "" ]
then
# MAC passed validation
	return 0
else
# MAC did not pass validation
	return 1
fi
}

# ****************************************************


# ****************************************************
# clean_read_value ()
# Usage: 
# echo -n Enter test string:\>
# read read_value
# echo  $(clean_read_value "$read_value")
# ****************************************************
clean_read_value ()
{
if [ ! $# -eq 0 ]
then
	local pattern=" "
	local RTN_VAL=`echo ${1##$pattern}`
	local RTN_VAL=`echo ${RTN_VAL%%$pattern}`
	local RTN_VAL=`echo ${RTN_VAL// /_}`
	echo ${RTN_VAL}
	return 0
fi

}
# ****************************************************


# ****************************************************
# add_mac_to_list ()
# function prompts user for input
# Usage: 
# if ( add_mac_to_list "$NEW_MAC" )
# then
# 	echo $NEW_MAC added to list
# else
# 	echo Failed to add $NEW_MAC
# fi
# ****************************************************
add_mac_to_list ()
{
local SVCTAG_VALUE=""
local SVCTAG_ANSWER=""
if ( ! validate_mac "$1" )
then
# MAC failed validation
	return 1
else
# MAC passed validation check duplication, read entry, validate/convert, add to mac.list
    if [ -f mac.list ]
    then
	# Check for duplicates
	local SEARCH_TABLE=`grep "$1" mac.list`
    else
	# If the table doesn't exist, then no duplicates
	SEARCH_TABLE=""
    fi
    if [ ! "$SEARCH_TABLE" = "" ]
    then
    # Found the address in the list.
	echo $1 already exists in table.
	return 1
    else
	echo -n Enter SVCTAG or 1 word description for $1:\>
	read SVCTAG_ANSWER
	if [ "$SVCTAG_ANSWER" = "" ]
	then 
		echo "Cannot be blank.  Using MAC as descriptor."
		SVCTAG_VALUE=$1
	else
	# strip leading/trailing spaces, then convert middle spaces to _
		SVCTAG_VALUE=$(clean_read_value "$SVCTAG_ANSWER")
	fi #if SVCTAG_ANSWER
	# Add the values to mac list
	echo $1 $SVCTAG_VALUE >> mac.list

	return 0
    fi #if grep
fi
}
# ****************************************************
